# -*- coding: utf-8 -*-
from cprt import createExtInfo, get_200_response,get_date_range
from cprt.accounts.models import UserDetail
from cprt.admin.models import Dept, get_my_depts, get_my_branchs2
from cprt.schedule.forms import ComposeScheduleForm
from cprt.schedule.models import ScheduleType, Schedule, TodoListSchedule
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import Context, RequestContext
from django.core.paginator import Paginator,PageNotAnInteger, EmptyPage



@login_required
def index(request):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))
    schedule_list = Schedule.objects.filter(created_by=request.user.id,start_date__gte=dt1.strftime("%Y-%m-%d"),end_date__lte=dt2.strftime("%Y-%m-%d"))
    paginator = Paginator(schedule_list,20)
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)

    c = RequestContext(request,{"list":data_list})
    c["dt1"]=dt1
    c["dt2"]=dt2
    createExtInfo(request,c)
    return render_to_response("schedule/list.html",c)

@login_required
def compose(request):
    if request.method == 'POST':
        form=ComposeScheduleForm(request.POST)
        if form.is_valid():
            form.save_form(created_by=request.user)
            return get_200_response("schedule_list_page","closeCurrent","/schedule/")
        else:
            errs=form.errors
    else:
        form = ComposeScheduleForm()
    c = RequestContext(request,{"form":form})
    c.update(csrf(request))
    createExtInfo(request,c)
    return render_to_response("schedule/compose.html",c)

@login_required
def edit(request, id):
    try:
        schedule=Schedule.objects.get(pk=id)
    except Schedule.DoesNotExist:
        raise Http404
    if schedule.created_by != request.user:
        raise Http404
    
    if request.method == 'POST':
        form = ComposeScheduleForm(request.POST, instance=schedule)
        if form.is_valid():
            form.save()
            return get_200_response("schedule_list_page","closeCurrent","/schedule/")
    else:
        c = RequestContext(request)
        c["form"]=ComposeScheduleForm(instance=schedule)
        c.update(csrf(request))
        createExtInfo(request, c)
        return render_to_response("schedule/edit.html",c)
    
@login_required
def commit(request, id):
    try:
        schedule=Schedule.objects.get(pk=id)
    except Schedule.DoesNotExist:
        raise Http404
    if schedule.status > 0 or schedule.created_by != request.user:
        raise Http404
    
    if request.method == 'POST':
        form = ComposeScheduleForm(request.POST, instance=schedule)
        if form.is_valid():
            form.commit_schedule()
            return get_200_response("schedule_list_page","closeCurrent","/schedule/")
    else:
        c = RequestContext(request)
        c["form"]=ComposeScheduleForm(instance=schedule)
        c.update(csrf(request))
        createExtInfo(request, c)
        return render_to_response("schedule/edit.html",c)
    
@login_required
def view(request,id):
    try:
        schedule=Schedule.objects.get(pk=id)
#        user=schedule.created_by #User.objects.get(pk=schedule.created_by)
    except Schedule.DoesNotExist:
        raise Http404
    c = RequestContext(request)
    c["schedule"] = schedule
#    c["created_by_user"]=user
    createExtInfo(request, c)
    return render_to_response("schedule/view.html",c) 
    
        

@login_required
def delete(request, id):
    try:
        schedule=Schedule.objects.get(pk=id)
    except Schedule.DoesNotExist:
        raise Http404
    
    if request.method == 'POST':
        if schedule.status > 0 or schedule.created_by != request.user:
            raise Http404
        schedule.delete()
        return get_200_response("schedule_list_page","closeCurrent","/schedule/")
    else:
        c = RequestContext(request)
        c["form"]=ComposeScheduleForm(instance=schedule)
        c.update(csrf(request))
        createExtInfo(request, c)
        return render_to_response("schedule/delete.html",c)
    
    

@login_required
def my_dept(request, id):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))
    try:
        dept = Dept.objects.get(pk=id)
    except Dept.DoesNotExist:
        raise Http404
    if dept == None or dept.principal_auth_user_id != request.user.id:
        raise Http404
    query_set = Schedule.objects.raw("select S.* from SCHEDULE S inner join USER_DETAIL U on S.created_by_id = U.user_id where S.start_date>= '%s' and S.end_date<='%s' and U.dept_id = %d" %(dt1.strftime("%Y-%m-%d"),dt2.strftime("%Y-%m-%d"),dept.id))
    paginator = Paginator(query_set,20)
    paginator._count = len(list(query_set))    
    
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    c = RequestContext(request,{"list":data_list})
    c["dt1"]=dt1
    c["dt2"]=dt2
    createExtInfo(request,c)
    return render_to_response("schedule/dept.html",c)

@login_required    
def branch(request,id):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))
    try:
        dept = Dept.objects.get(pk=id)
    except Dept.DoesNotExist:
        raise Http404
    branchs = get_my_branchs2(request.user.id)
    if dept == None or dept not in branchs:
        raise Http404
    query_set = Schedule.objects.raw("select S.* from SCHEDULE S inner join USER_DETAIL U on S.created_by_id = U.user_id where S.start_date >= '%s' and S.end_date <= '%s' and U.dept_id = %s" %(dt1.strftime("%Y-%m-%d"),dt2.strftime("%Y-%m-%d"), id))
    paginator = Paginator(query_set,20)
    paginator._count = len(list(query_set))    
    
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    
    c = RequestContext(request,{"list":data_list})
    c["dt1"]=dt1
    c["dt2"]=dt2    
    createExtInfo(request,c)
    return render_to_response("schedule/dept.html",c)

@login_required
def view_by_user(request, uid):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))
    try:
        from django.contrib.auth.models import User
        user = User.objects.get(pk=uid)
    except User.DoesNotExist:
        raise Http404
    if user.id != request.user.id and not request.META["management_role"]:
        raise Http404
    
    schedule_list = Schedule.objects.filter(created_by=user.id,start_date__gte=dt1.strftime("%Y-%m-%d"),end_date__lte=dt2.strftime("%Y-%m-%d"))
    paginator = Paginator(schedule_list,20)
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)

    
    c = RequestContext(request,{"list":data_list})
    c["dt1"]=dt1
    c["dt2"]=dt2    
    createExtInfo(request,c)
    return render_to_response("schedule/list.html",c)

@login_required
def list_todo_list_schedule(request):
    pn = int(request.GET.get('pageNum',1))
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))
    todo_list = TodoListSchedule.objects.filter(auth_user=request.user,start_date__gte=dt1.strftime("%Y-%m-%d"),end_date__lte=dt2.strftime("%Y-%m-%d"))
    paginator = Paginator(todo_list,20)
    try:
        data_list = paginator.page(pn)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    
    c = RequestContext(request,{"list":data_list})
    c["dt1"]=dt1
    c["dt2"]=dt2    
    createExtInfo(request,c)
    return render_to_response("schedule/todo_list.html",c)
